import 'package:flutter/foundation.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/mode/inspiration/inspiration_page.dart';
import 'package:loxen/mode/like_bean.dart';
import 'package:loxen/mode/material/material_item.dart';
import 'package:loxen/mode/material/material_list_bean.dart';
import 'package:loxen/mode/study/study_bean.dart';
import 'package:loxen/mode/study/study_info_bean.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:rxdart/rxdart.dart';

enum SearchType { INSPIRATION, MATERIAL, KNOWLEDGE, CASE }

class SearchResultViewModel extends BaseViewModel {
  int _studyCategory = 0;
  SearchType _type;
  String _data;
  Map<String, List<dynamic>> _map = Map();

  int get studyCategory => _studyCategory;

  List<String> types = ['knowledge', 'case'];

  String getTypeUrl() {
    if (_type == SearchType.INSPIRATION) {
      return 'idea-article';
    }
    if (_type == SearchType.MATERIAL) {
      return 'material-product';
    }
    if (_type == SearchType.KNOWLEDGE) {
      return 'study-knowledge';
    }
    if (_type == SearchType.CASE) {
      return 'study-case';
    }
    return "";
  }

  void changeCurrentCategory(int category) {
    _studyCategory = category;
    notifyListeners();
  }

  void unCollection(String id,
      {Function() onSuccess, Function(String error) onError}) {
    ApiService.unCollection(getTypeUrl(), id).listen((event) {
      if (event.statusCode == 200) {
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onError != null) onError.call(event.data.toString());
      }
    }, onError: (error, stack) {
      if (onError != null) onError.call(error.toString());
      print(error);
      print(stack);
    }, onDone: () => notifyListeners());
  }

  //点赞
  void like(InspirationInfo entity) {
    if (entity != null) {
      if (entity.is_like == 0) {
        ApiService.likeArticle(entity.id.toString())
            .flatMap((value) => compute(decodeLikeBean, value.data).asStream())
            .listen((event) {
          if (event.code == 2000) {
            entity.is_like = 1;
            entity.like_num = event.data.like_num;
            notifyListeners();
          }
        }, onError: (error) => print(error));
      } else {
        //取消点赞
        ApiService.unLikeArticle(entity.id.toString())
            .flatMap((value) => compute(decodeLikeBean, value.data).asStream())
            .listen((event) {
          if (event.code == 2000) {
            entity.is_like = 0;
            entity.like_num = event.data.like_num;
            notifyListeners();
          }
        }, onError: (error) => print(error));
      }
    }
  }

  //点赞
  void likeStudy(StudyInfo entity) {
    if (entity != null) {
      if (entity.is_like == 0) {
        ApiService.likeStudy(entity.id.toString(), types[_studyCategory])
            .flatMap((value) => compute(decodeLikeBean, value.data).asStream())
            .listen((event) {
          if (event.code == 2000) {
            entity.is_like = 1;
            entity.like_num = event.data.like_num;
            notifyListeners();
          }
        }, onError: (error) => print(error));
      } else {
        //取消点赞
        ApiService.unLikeStudy(entity.id.toString(), types[_studyCategory])
            .flatMap((value) => compute(decodeLikeBean, value.data).asStream())
            .listen((event) {
          if (event.code == 2000) {
            entity.is_like = 0;
            entity.like_num = event.data.like_num;
            notifyListeners();
          }
        }, onError: (error) => print(error));
      }
    }
  }

  Future<List<MaterialItem>> nextMaterialData(int page) async {
    if (_map.containsKey(page.toString())) {
      return _map[page.toString()];
    } else {
      var data = await ApiService.materialProduct(
              search: _data, page: (page += 1).toString())
          .flatMap(
              (value) => compute(decodeMaterialListBean, value.data).asStream())
          .first;
      _map.putIfAbsent(page.toString(), () => data.data.results);
      return data.data.results;
    }
  }

  Future<List<InspirationInfo>> nextInspirationData(int page) async {
    if (_map.containsKey(page.toString())) {
      return _map[page.toString()];
    } else {
      var resp = await ApiService.searchInspiration(
              _data, (page + 1).toString())
          .flatMap(
              (value) => compute(decodeInspirationBean, value.data).asStream())
          .first;
      _map[page.toString()] = resp.data.results;
      return resp.data.results;
    }
  }

  Future<List<StudyInfo>> nextStudyData(int page) async {
    print('请求数据');
    if (_map.containsKey('${types[_studyCategory]}$page')) {
      return _map['${types[_studyCategory]}$page'];
    } else {
      var resp = await ApiService.searchStudy(
              types[_studyCategory], _data, (page + 1).toString())
          .flatMap((value) => compute(decodeStudyBean, value.data).asStream())
          .first;
      _map['${types[_studyCategory]}$page'] = resp.data.results;
      return resp.data.results;
    }
  }

  void loadData({int studyCategory, SearchType type, String data}) {
    if (_type == null) {
      _type = type;
      _data = data;
    }
    if (type == SearchType.INSPIRATION) {
      loadInspirationData(data);
    } else if (type == SearchType.MATERIAL) {
      loadMaterial(data);
    } else if (type == SearchType.KNOWLEDGE) {
      loadStudy(studyCategory, data);
    } else if (type == SearchType.CASE) {
      loadStudy(studyCategory, data);
    }
  }

  //展示查询默认为5个
  void loadInspirationData(String data) {
    if (mState == BaseState.LOADING) return;
    ApiService.searchInspiration(data, '1')
        .doOnListen(() {
          mState = BaseState.LOADING;
        })
        .flatMap(
            (value) => compute(decodeInspirationBean, value.data).asStream())
        .listen((event) {
          if (event.data.count > 0) {
            mState = BaseState.CONTENT;
            _map['0'] = event.data.results;
          } else {
            mState = BaseState.EMPTY;
          }
        }, onError: (error, stack) {
          mState = BaseState.FAIL;
          print(error);
          print(stack);
        }, onDone: () => notifyListeners());
  }

  //加载素材数据   8个一页
  void loadMaterial(String data) {
    if (mState == BaseState.LOADING) return;
    ApiService.materialProduct(search: data)
        .doOnListen(() {
          mState = BaseState.LOADING;
        })
        .flatMap(
            (value) => compute(decodeMaterialListBean, value.data).asStream())
        .listen((event) {
          if (event.data.results.length > 0) {
            mState = BaseState.CONTENT;
            _map.putIfAbsent('0', () => event.data.results);
          } else {
            mState = BaseState.EMPTY;
          }
        }, onError: (error, stack) {
          mState = BaseState.FAIL;
          print(error);
          print(stack);
        }, onDone: () => notifyListeners());
  }

  //展示查询默认为5个
  void loadStudy(int studyCategory, String data) {
    if (mState == BaseState.LOADING) return;
    ApiService.searchStudy(types[studyCategory], data, '1')
        .doOnListen(() {
          mState = BaseState.LOADING;
        })
        .flatMap((value) => compute(decodeStudyBean, value.data).asStream())
        .listen((event) {
          if (event.data.results.length > 0) {
            mState = BaseState.CONTENT;
            _map.putIfAbsent(
                '${types[studyCategory]}0', () => event.data.results);
          } else {
            mState = BaseState.EMPTY;
          }
        }, onError: (error) {
          mState = BaseState.FAIL;
          print(error);
        }, onDone: () => notifyListeners());
  }

  static MaterialListBean decodeMaterialListBean(dynamic json) {
    return MaterialListBean.fromJson(json);
  }

  //
  static BaseMode<InspirationPage> decodeInspirationBean(dynamic json) {
    return BaseMode<InspirationPage>(json);
  }

  static LikeBean decodeLikeBean(dynamic json) {
    return LikeBean.fromJson(json);
  }

  static StudyBean decodeStudyBean(dynamic json) {
    return StudyBean.fromJson(json);
  }

  void refresh() {
    _map.clear();
  }

  void changeEntity() {
    notifyListeners();
  }
}
